/***
 * 将目录下的小图合成一张大图集(texture)
 * 设定最大宽高,以单行最高的单张图为单行高度,逐行排序,
 * 生成含坐标的.json索引文件
 */

var images = require("images");
var fs = require('fs');



function windowPath2UnixPath(path) {
    return path.split('\\').join('/');
}

var testJson = "{\"file\":\"login.png\",\"frames\":{\"login_73\":{\"login_73\":{\"x\":800,\"y\":471,\"w\":298,\"h\":416,\"offX\":0,\"offY\":1,\"sourceW\":300,\"sourceH\":417}}}}";


var json = JSON.parse(testJson);


var jsonArray = json.frames;
var newFrames = {};
for (var key1 in jsonArray) {
    var item = jsonArray[key1];
    for (var key in item) {
        newFrames[key] = item[key];
    }
}

json["frames"] = newFrames;
console.log("[INFO] save json to : " + JSON.stringify(json));



function renameFrames(path) {

    var json = JSON.parse(fs.readFileSync(path, "UTF-8"));
    var jsonArray = json.frames;
    var newFrames = {};
    for (var key1 in jsonArray) {
        var item = jsonArray[key1];
        for (var key in item) {
            newFrames[key] = item[key];
        }
    }
    json["frames"] = newFrames;

    fs.writeFileSync(path, JSON.stringify(json));
    // console.log("[INFO] save json to : " + json);
}

var paths = [];

var rootDir = "D:\\M2\\M2\\Texture";
var children = fs.readdirSync(rootDir).filter(function (s) {
    return s.lastIndexOf(".wil.json") > 0;
});
for (var j = 0; j <= children.length; j++) {
    paths.push(rootDir + "/" + children[j]);
}
for (var i in paths) {
    try {
        renameFrames(paths[i]);
    } catch (e) {
        console.log("[ERR ]  " + JSON.stringify(e));
    }

}

console.log("  success!!! ");